/**
 * Copyright &copy; 2013-2016 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.cms.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.mapper.JsonMapper;
import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.cms.entity.Article;
import cn.net.ecode.modules.cms.entity.ArticleData;
import cn.net.ecode.modules.cms.entity.Category;
import cn.net.ecode.modules.cms.entity.Site;
import cn.net.ecode.modules.cms.service.ArticleService;
import cn.net.ecode.modules.cms.service.CategoryService;
import cn.net.ecode.modules.cms.service.FileTplService;
import cn.net.ecode.modules.cms.utils.CmsUtils;

/**
 * 文章Controller
 * @author ThinkGem
 * @version 2014-9-16
 */
@Controller
@RequestMapping(value = "${adminPath}/cms/article")
public class ArticleController extends BaseController {

	@Autowired
	private ArticleService articleService;
	@Autowired
	private CategoryService categoryService;
    @Autowired
   	private FileTplService fileTplService;
	
	@ModelAttribute
	public Article get(String id, boolean isNewRecord) {
		return articleService.get(id, isNewRecord);
	}
	
//	@RequiresPermissions("cms:article:view")
	@RequestMapping(value = {"list", ""})
	public String list(Article article, String canAdmin, Boolean isAll, Model model) {
		if (article.getCategory() != null && StringUtils.isNotBlank(article.getCategory().getCategoryCode()) 
				&& !Category.ROOT_CODE.equals(article.getCategory().getId())){
			article.setCategory(CmsUtils.getCategory(article.getCategory().getId()));
		}else{
			Category category = new Category();
			category.setCategoryName("内容列表");
			article.setCategory(category);
		}
		// 栏目展现模式，当为（2：简介类栏目，栏目第一条内容）时，自动维护第一条内容
		if ("2".equals(article.getCategory().getShowModes())){
			// 获取文章内容
			Page<Article> page = new Page<Article>(1, 1, -1);
			// 管理栏目的时候查询全部文章
			if ("true".equals(canAdmin)){
				article.setStatus(null);
			}
			page = articleService.findPage(page, article, false);
			if (page.getList().size()>0){
				article = page.getList().get(0);
				article.setArticleData(articleService.get(new ArticleData(article.getId())));
			}
			// 管理栏目的时候进行编辑文章
			if ("true".equals(canAdmin)){
				return form(article, model);	
			}else{
				return view(article, model);
			}
		}
		model.addAttribute("canAdmin", canAdmin);
		model.addAttribute("isAll", isAll);
		return "modules/cms/articleList";
	}
	
	/** 
	 * 文章列表数据
	 * @param article
	 * @param canAdmin 传递true，返回当前用户能管理的文章列表
	 */
//	@RequiresPermissions("cms:article:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public Page<Article> listData(Article article, String canAdmin, Boolean isAll, HttpServletRequest request, HttpServletResponse response, Model model) {
		logger.debug("categoryCod:{}",article.getCategory().getCategoryCode());
		article.setCategoryCode(article.getCategory().getCategoryCode());
		Page<Article> page= articleService.findPage(new Page<Article>(request, response), article, !(isAll != null && isAll));
		return page;
	}

	@RequiresPermissions("cms:article:edit")
	@RequestMapping(value = "form")
	public String form(Article article, Model model) {
		// 如果当前传参有子节点，则选择取消传参选择（不允许在父级上添加文章）
		if (article.getCategory() != null && StringUtils.isNotBlank(article.getCategory().getCategoryCode())){
			Category categoryParam = new Category();
			categoryParam.setSite(new Site(Site.getCurrentSiteCode()));
			categoryParam.setParentCode(article.getCategory().getCategoryCode());
			List<Category> list = categoryService.findList(categoryParam);
			if (list.size() > 0){
				article.setCategory(null);
			}else{
				Category category=categoryService.get(article.getCategory().getId());
				article.setCategory(category);
				article.setCategoryCode(category.getId());
				article.setCategoryName(category.getCategoryName());
			}
		}
//		if (article.getCategory()=null && StringUtils.isNotBlank(article.getCategory().getId())){
//			Category category = categoryService.get(article.getCategory().getId());
//		}
		if(StringUtils.isBlank(article.getId())){
			article.setStatus(Article.STATUS_DRAFT);
		}
        model.addAttribute("contentViewList", fileTplService.getTplContent(Article.DEFAULT_TEMPLATE));
        model.addAttribute("article_DEFAULT_TEMPLATE", Article.DEFAULT_TEMPLATE);
		model.addAttribute("article", article);
		CmsUtils.addViewConfigAttribute(model, article.getCategory());
		return "modules/cms/articleForm";
	}
	
	/**
	 * 文章详情查看
	 * @param article
	 * @param model
	 * @return
	 */
//	@RequiresPermissions("cms:article:view")
	@RequestMapping(value = "view")
	public String view(Article article, Model model) {
		// 文章阅读次数+1
		articleService.updateHitsAddOne(article.getId());
		
		model.addAttribute("article", article);
		model.addAttribute("category", article.getCategory());
        model.addAttribute("site", article.getCategory().getSite());
        CmsUtils.addViewConfigAttribute(model, article.getCategory());
        CmsUtils.addViewConfigAttribute(model, article.getViewConfig());
		return "modules/cms/articleView";
	}

	@RequiresPermissions("cms:article:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(Article article, Model model, RedirectAttributes redirectAttributes) {
		logger.debug("status:{}",article.getStatus());
		StringBuilder message = new StringBuilder();
		if (!beanValidator(message, article)){
			return renderResult(Global.FALSE, message);
		}
		articleService.save(article);
		return renderResult(Global.TRUE, "保存文章'" + StringUtils.abbr(article.getTitle(),50) + "'成功");
	}
	
	@RequiresPermissions("cms:article:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(Article article, String categoryId, Boolean isRe, RedirectAttributes redirectAttributes) {
		// 如果没有审核权限，则不允许删除或发布。
		/*if (!UserUtils.getSubject().isPermitted("cms:article:audit")){
			return renderResult(Global.FALSE, "你没有删除或发布权限");
		}*/
		articleService.delete(article, isRe);
		return renderResult(Global.TRUE, (isRe!=null&&isRe?"发布":"删除")+"文章成功");
	}

	/**
	 * 文章选择列表
	 */
//	@RequiresPermissions("cms:article:view")
	@RequestMapping(value = "selectList")
	public String selectList(Article article, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/cms/articleSelectList";
	}
	
	/**
	 * 通过编号获取文章标题
	 */
//	@RequiresPermissions("cms:article:view")
	@ResponseBody
	@RequestMapping(value = "findByIds")
	public String findByIds(String ids) {
		List<Object[]> list = articleService.findByIds(ids);
		return JsonMapper.nonDefaultMapper().toJson(list);
	}
}
